package com.han.demo.transaction;

import com.han.demo.entity.User;
import com.han.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author hanjl
 * @Description 不使用事务，如果当前事务存在，则抛出异常
 * @ClassName Never
 * @createTime 2021/11/18 17:31
 */
@Service
public class Never {

    @Resource
    private UserMapper userMapper;
    /**
     * 加上@Transactional注解会生成Mandatory的代理对象，如果不用生成的代理对象去调用testB
     * 则事务的传播规则会失效。因为不用代理对象去调用，就还是没有加事务的普通对象去调用的，事务的传播机制就会失效
     */
    @Autowired
    private Never never;

    @Transactional(propagation = Propagation.REQUIRED)
    public void testMain(){
        User a = new User();
        a.setName("required");
        A(a);
        never.testB();
    }
    @Transactional(propagation = Propagation.NEVER)
    public void testB(){
        User b = new User();
        b.setName("required2");
        B(b);

        User b2 = new User();
        b2.setName("required3");
        B(b2);
    }

    public void A(User user){
        userMapper.insert(user);
    }

    public void B(User user){
        userMapper.insert(user);
    }
}
